<template>
    <div class="profile-container">
        <!-- 顶部导航栏 -->
        <HeaderNav active-menu="profile" />

        <div class="profile-content">
            <div class="profile-wrapper">
                <!-- 个人资料卡片 -->
                <el-card class="profile-card">
                    <template #header>
                        <div class="card-header">
                            <h2>个人资料</h2>
                            <div class="header-actions">
                                <el-button type="primary" @click="editProfile">编辑资料</el-button>
                                <el-button @click="backTohome">返回</el-button>
                            </div>
                        </div>
                    </template>

                    <div class="profile-info">
                        <!-- 头像区域 -->
                        <div class="avatar-section">
                            <AvatarUpload :size="120" :avatar-url="userInfo.avatar"
                                @update:avatar-url="handleAvatarUpdate" @upload-success="handleUploadSuccess" />
                            <div class="avatar-tip">点击头像可上传新头像</div>
                        </div>

                        <!-- 基本信息 -->
                        <div class="info-section">
                            <h3 class="section-title">基本信息</h3>
                            <div class="info-row">
                                <label>昵称：</label>
                                <span class="info-value">{{ userInfo.nickname || '未设置' }}</span>
                            </div>
                            <div class="info-row">
                                <label>手机号：</label>
                                <span class="info-value">{{ userInfo.phone || '未设置' }}</span>
                            </div>
                            <div class="info-row">
                                <label>邮箱：</label>
                                <span class="info-value">{{ userInfo.email }}</span>
                            </div>
                            <div class="info-row">
                                <label>性别：</label>
                                <span class="info-value">{{ formatGender(userInfo.gender) }}</span>
                            </div>
                        </div>

                        <!-- 职业信息 -->
                        <div class="info-section">
                            <h3 class="section-title">职业信息</h3>
                            <div class="info-row">
                                <label>所在城市：</label>
                                <span class="info-value">{{ userInfo.city || '未设置' }}</span>
                            </div>
                            <div class="info-row">
                                <label>公司：</label>
                                <span class="info-value">{{ userInfo.company || '未设置' }}</span>
                            </div>
                            <div class="info-row">
                                <label>职位：</label>
                                <span class="info-value">{{ userInfo.position || '未设置' }}</span>
                            </div>
                        </div>

                        <!-- 详细信息 -->
                        <div class="info-section">
                            <h3 class="section-title">详细信息</h3>
                            <div class="info-row">
                                <label>个人简介：</label>
                                <span class="info-value bio-text">{{ userInfo.bio || '暂无简介' }}</span>
                            </div>
                            <div class="info-row">
                                <label>地址：</label>
                                <span class="info-value">{{ userInfo.address || '未设置' }}</span>
                            </div>
                        </div>

                        <!-- 验证信息 -->
                        <div class="info-section verification-section">
                            <h3 class="section-title">校友验证信息</h3>
                            <div class="info-row">
                                <label>真实姓名：</label>
                                <span class="info-value">{{ userInfo.real_name || '未验证' }}</span>
                                <el-tag v-if="!userInfo.real_name" type="warning" size="small">未验证</el-tag>
                                <el-tag v-else type="success" size="small">已验证</el-tag>
                            </div>
                            <div class="info-row">
                                <label>学号：</label>
                                <span class="info-value">{{ userInfo.student_id || '未验证' }}</span>
                                <el-tag v-if="!userInfo.student_id" type="warning" size="small">未验证</el-tag>
                                <el-tag v-else type="success" size="small">已验证</el-tag>
                            </div>
                            <div class="verification-tip" @click="openVerificationDialog" style="cursor: pointer;">
                                <el-icon>
                                    <InfoFilled />
                                </el-icon>
                                <span>点击去校友信息验证</span>
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 编辑资料对话框 -->
        <ProfileEdit v-model="editDialogVisible" :user-info="userInfo" @success="handleEditSuccess" />

        <!-- 校友认证对话框 -->
        <el-dialog v-model="verificationDialogVisible" title="校友信息验证" width="500px"
            :before-close="handleCloseVerification">
            <el-form ref="verificationFormRef" :model="verificationForm" :rules="verificationRules" label-width="100px">
                <el-form-item label="学号" prop="student_id">
                    <el-input v-model="verificationForm.student_id" placeholder="请输入学号" maxlength="20" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="real_name">
                    <el-input v-model="verificationForm.real_name" placeholder="请输入真实姓名" maxlength="50" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="verificationForm.phone" placeholder="请输入手机号" maxlength="11" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCloseVerification">取消</el-button>
                    <el-button type="primary" @click="handleVerification" :loading="verifying">
                        验证
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useAlumniStore } from '@/stores/alumni'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import AvatarUpload from '@/components/upload/AvatarUpload.vue'
import ProfileEdit from '@/components/profile/ProfileEdit.vue'

const router = useRouter()
const userStore = useUserStore()
const alumniStore = useAlumniStore()

// 响应式数据
const editDialogVisible = ref(false)
const verificationDialogVisible = ref(false)
const verifying = ref(false)
const verificationFormRef = ref(null)

// 验证表单
const verificationForm = ref({
    student_id: '',
    real_name: '',
    phone: ''
})

// 验证规则
const verificationRules = {
    student_id: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { min: 12, max: 12, message: '长度在 12 个字符', trigger: 'blur' }
    ],
    real_name: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
}

// 计算属性
const userInfo = computed(() => {
    return userStore.userInfo
})

const editProfile = () => {
    editDialogVisible.value = true
}

const backTohome = async () => {
    router.push('/')
}

const handleAvatarUpdate = (newAvatarUrl) => {
    console.log('头像URL更新:', newAvatarUrl)
}

const handleUploadSuccess = (avatarUrl) => {

}

const handleEditSuccess = () => {
    // 编辑成功后的回调
    ElMessage.success('资料更新成功')
}

const formatGender = (gender) => {
    const genderMap = {
        0: '未知',
        1: '男',
        2: '女'
    }
    return genderMap[gender] || '未知'
}

// 打开校友认证对话框
const openVerificationDialog = () => {
    verificationDialogVisible.value = true
    // 重置表单
    if (verificationFormRef.value) {
        verificationFormRef.value.resetFields()
    }
}

// 关闭校友认证对话框
const handleCloseVerification = () => {
    verificationDialogVisible.value = false
    verificationForm.value = {
        student_id: '',
        real_name: '',
        phone: ''
    }
    if (verificationFormRef.value) {
        verificationFormRef.value.clearValidate()
    }
}

// 处理校友认证
const handleVerification = async () => {
    if (!verificationFormRef.value) return

    try {
        // 表单验证
        await verificationFormRef.value.validate()
        verifying.value = true

        // 调用校友认证接口
        const response = await alumniStore.verifyAlumniAction(verificationForm.value)

        if (response.code === 0) {
            ElMessage.success('校友认证成功')

            // 更新用户信息
            await userStore.updateUserInfo({
                real_name: verificationForm.value.real_name,
                student_id: verificationForm.value.student_id,
                phone: verificationForm.value.phone,
                verification_status: 1 // 用户表认证状态改为1（已认证）
            })

            // 刷新用户信息
            await userStore.refreshUserInfo()

            // 关闭对话框
            handleCloseVerification()
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.warning('请完善验证信息')
        } else {
            ElMessage.error('校友认证失败：' + error.message)
        }
    } finally {
        verifying.value = false
    }
}
</script>

<style scoped>
.profile-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f7fa;
}

.profile-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
}

.profile-wrapper {
    max-width: 800px;
    margin: 0 auto;
}

.profile-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h2 {
    margin: 0;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.profile-info {
    display: flex;
    flex-direction: column;
    gap: 32px;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.avatar-tip {
    font-size: 12px;
    color: #909399;
}

.info-section {
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.section-title {
    margin: 0 0 16px 0;
    font-size: 16px;
    color: #303133;
    font-weight: 600;
}

.info-row {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #e8e8e8;
}

.info-row:last-child {
    border-bottom: none;
}

.info-row label {
    width: 100px;
    font-weight: 500;
    color: #606266;
    flex-shrink: 0;
}

.info-value {
    flex: 1;
    color: #303133;
}

.bio-text {
    line-height: 1.5;
    white-space: pre-wrap;
}

.verification-section {
    background: #f0f9ff;
    border: 1px solid #e1f5fe;
}

.verification-tip {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 12px;
    padding: 8px 12px;
    background: #e6f7ff;
    border-radius: 4px;
    font-size: 12px;
    color: #1890ff;
}

.verification-tip .el-icon {
    font-size: 14px;
}
</style>